/**
 * 中国9号健康产业有限公司
 * Copyright (C) JiuHaoHealth Corporation. All Rights Reserved
 */
package com.jiuhaohealth.common.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
/**
 * @author minghui(jackchenmh@gmail.com)
 * @version 2014-3-18 下午5:08:45
 */
public class JsonUtil {

	public static String objectToJson(Object obj) {
		return JSONObject.fromObject(obj).toString();
	}

	public static <T>List<T> jsonArrayToList(String json, Class<T> cs) {
		JSONArray jArray = JSONArray.fromObject(json);
		List<T> list = new ArrayList<T>();
		for (int i = 0; i < jArray.size(); i++) {
			JSONObject jObject = jArray.getJSONObject(i);
			list.add((T)JSONObject.toBean(jObject, cs));
		}
		return list;
	}	
	
	public static String getFieldFromJson(String json, String field) {
		JSONObject jObject = JSONObject.fromObject(json);
		return (String)jObject.get(field);
	}
	
	public static String listToJson(List<?> list) {
		JSONArray array = JSONArray.fromObject(list);
		return array.toString();
	}
	
	public static String listToJson(List<?> rs, PropertyFilter fs) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJsonPropertyFilter(fs);
		JSONArray json = JSONArray.fromObject(rs, jsonConfig);
    	return json.toString();
	}
	
	public static String toJsonArray(PropertyFilter fs, Object ... para) {
		
		JSONArray json = new JSONArray();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJsonPropertyFilter(fs);
		for (Object o : para) {
			JSONArray js = JSONArray.fromObject(o, jsonConfig);
			json.add(js);
		}
    	return json.toString();
	}
	
	public static String getJsonFromObject(Object object) {
		JSONObject jObject = JSONObject.fromObject(object);
		return jObject.toString();
	}
	
	public static String getJsonFromObject(Object object, PropertyFilter fs) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJsonPropertyFilter(fs);
		JSONObject jObject = JSONObject.fromObject(object, jsonConfig);
		return jObject.toString();
	}
	
	public static <T> T getObjectFromJson(String json, Class<T> clazz) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		return (T)JSONObject.toBean(jsonObject, clazz);
	}
	
	
	public static void main(String[] args) {
		
	}
	
}
